package com.lyh.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyh.db137.common.R;
import com.lyh.db137.entity.Role;
import com.lyh.db137.entity.Userrole;
import com.lyh.db137.service.RoleService;
import com.lyh.db137.service.UserroleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: 想要告诉你
 * @CreateTime: 2025/1/3 09:45
 * @Description:
 * @Version: 1.0
 */

@RestController
@CrossOrigin(origins = "*")
public class UserroleController {
    @Autowired
    private UserroleService userroleService;
    @RequestMapping("/selectRoleByUserId")
    public R selectRoleByUserId(Integer uid) {
        List<Role> userRoleList = userroleService.selectRoleByUserId(uid);
        return new R().addData("userRoleList", userRoleList);
    }

    //根据userid批量删除
    @RequestMapping("/deleteUserroleByUserId")
    public R deleteUserrole(Integer uid) {
        if (uid != null && uid > 0){
            QueryWrapper<Userrole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userid",uid);
            userroleService.remove(queryWrapper);
            return new R().setCode(200).setMessage("删除成功");
        }else {
            return new R().setCode(500).setMessage("无需删除的东西");
        }
    }

    //批量插入
    @RequestMapping("/addUserrole")
    public R addUserrole(Integer uid, String roleids) {
        roleids = roleids.substring(0, roleids.length() - 1);
        String[] roleid = roleids.split(",");
        int i = 0;
        for (String s : roleid) {
            Userrole userrole = new Userrole();
            userrole.setUserid(uid);
            userrole.setRoleid(Integer.parseInt(s));
            boolean b = userroleService.save(userrole);
            if (b){
                i++;
            }
        }
        if (i == roleid.length){
            return new R().setCode(200).setMessage("全部添加成功！");
        }else if (i != 0){
            return new R().setCode(200).setMessage(i + "个添加成功，" + (roleid.length - i) + "个添加失败！");
        }else {
            return new R().setCode(500).setMessage("全部添加失败！");
        }
    }
}
